package com.lc;

import com.alibaba.fastjson.JSONObject;
import com.lc.es.ESConfig;
import com.lc.es.ElasticsearchUtils;
import com.lc.es.bean.Field;
import com.lc.es.bean.QueryBean;
import org.assertj.core.util.Lists;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.client.indices.GetIndexResponse;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.xcontent.XContentType;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.util.*;

import static com.lc.es.ElasticsearchUtils.getFieldMap;

@SpringBootApplication
public class SpringBootMain {
    public static void main(String[] args) {
        SpringApplication.run(SpringBootMain.class,args);
    }

    static ElasticsearchUtils elasticsearchUtils;
    static {
        elasticsearchUtils = new ElasticsearchUtils("192.168.66.178:19201,192.168.66.179:19201,192.168.66.180:19201", "elastic", "123456");
    }

    @PostConstruct
    public void Test() throws IOException {
//        testGetIndex();
//        testMapping();
//        testGetMappingFields();
//        testGetFields();

        // TODO
        // QueryBean relationParam = getRelationParam("vid1", "vid2", 1, Lists.list(1,2,3));
        // List<JSONObject> test = elasticsearchUtils.searchDocs("test",relationParam);
//        Map<String, String> fieldMap = getFieldMap("field_keyword");
//        System.out.println(fieldMap);
//        List<String> indices = elasticsearchUtils.getIndices();
//        System.out.println(indices);


//        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
//        String [] index = {"test"};
//        ElasticsearchUtils.searchAll(elasticsearchUtils.getClient(), searchSourceBuilder, index);

        String sql = "SELECT\n" +
                "  id\n" +
                ", user_id\n" +
                ", user_name\n" +
                ", work_code\n" +
                ", name\n" +
                ", oper_time\n" +
                ", application_code\n" +
                ", resource_code\n" +
                ", type\n" +
                ", url\n" +
                ", ip\n" +
                ", time_consum\n" +
                ", is_success\n" +
                ", remark\n" +
                ", in_param\n" +
                ", start_time-date\n" +
                ", end_time-date\n" +
                ", response_raw_json\n" +
                ", response_time\n" +
                ", method\n" +
                ", path\n" +
                ", message\n" +
                ", request_flag\n" +
                "FROM sys_log";
        //to_char(sysdate,'yy-mm-dd hh24:mi:ss')

        getSql(sql);

        System.out.println("----------------------------------上SQL、下mapping---------------------------------------\n");

        getMapping(sql);
    }

    public void getSql(String sql){
        StringBuilder result = new StringBuilder();
        String[] split = sql.split(",");
        int count = 0;
        for (String s : split) {
            count++;
            // -date 数据
            String[] split1 = s.split("-");
            if (split1.length >= 2 ){
                String s1 = split1[0];
                String s2 = s1.replaceAll("\n", "");
                s2 = "to_char(" + s2 + ",'yy-mm-dd hh24:mi:ss')";
                result.append(s2 + "\n"+ ",");
            }else {
                if (count == split.length){
                    result.append(s);
                }else {
                    result.append(s+",");
                }
            }
        }
        System.out.println(result);
    }

    public void getMapping(String sql){
        String[] split = sql.split(",");
        JSONObject jsonObject0 = new JSONObject();
        int count = 0;
        for (String s : split) {
            count++;
            // -date 数据
            String[] split1 = s.split("-");
            if (split1.length >= 2 ){
                String s1 = split1[0];
                String s2 = s1.replaceAll("\n", "");
                JSONObject jsonObject1 = new JSONObject();
                jsonObject1.put("type","date");
                jsonObject1.put("format","yyyy-MM-dd HH:mm:ss");
                jsonObject0.put(s2,jsonObject1);
            }else {
                String s1 = "";
                for (int i = 0; i < split1.length; i++) {
                    if (split1[i].startsWith("SELECT")){
                        // 获取 select 边上的 查询字段
                        String[] split2 = split1[i].split(" ");
                        s1 = split2[2];
                    }
                    if (count == split.length){
                        // 获取最后一个字段
                        String[] split2 = split1[i].split("FROM");
                        s1 = split2[0];
                    }

                }

                JSONObject jsonObject1 = new JSONObject();
                jsonObject1.put("type","keyword");
                if (s1.equals("")){
                    // 如果是中间字段
                    s1 = s.replaceAll("\n", "");
                }else {
                    // 如果是开头或者是结束的字段
                    s1 = s1.replaceAll("\n", "");
                }

                // 去掉所有的空格
                s1 = s1.replaceAll(" ", "");
                jsonObject0.put(s1,jsonObject1);
            }
        }
        System.out.println(jsonObject0);
    }



    public void testGetFields(){
        List<Field> test = elasticsearchUtils.getFields("test");
        System.out.println(test);
    }


    public static void testGetMappingFields(){
        JSONObject test = elasticsearchUtils.getMappingFields("test");
        System.out.println(test);
    }

    public void testMapping(){
        ElasticsearchUtils elastic = new ElasticsearchUtils("192.168.66.175:19201,192.168.66.176:19201,192.168.66.177:19201", "elastic", "123456");
        JSONObject test = elastic.getMapping("test");
        JSONObject jsonObject = test.getJSONObject("properties");
        System.out.println(jsonObject);
    }

    public void testGetIndex(){
        ElasticsearchUtils elasticsearchUtils = new ElasticsearchUtils("192.168.66.175:19201,192.168.66.176:19201,192.168.66.177:19201", "elastic", "123456");
        GetIndexResponse test = elasticsearchUtils.getIndex("test");
        System.out.println(test);
    }

    public void testElasticsearchUtils() throws IOException {
        ElasticsearchUtils elastic = new ElasticsearchUtils("192.168.66.175:19201,192.168.66.176:19201,192.168.66.177:19201", "elastic", "123456");
        RestHighLevelClient client = elastic.getClient();
        GetIndexResponse test = client.indices().get(new GetIndexRequest("test"), RequestOptions.DEFAULT);
        System.out.println(test);
    }

    public void testConfig() throws IOException {
        ESConfig esConfig = new ESConfig();
        RestHighLevelClient restHighLevelClient = esConfig.getRestHighLevelClient();
        System.out.println(restHighLevelClient);
        GetIndexResponse test = restHighLevelClient.indices().get(new GetIndexRequest("test"), RequestOptions.DEFAULT);
        System.out.println(test);
    }

    public static <T0,T1> QueryBean getRelationParam(String param0,String param3,T0 id, T1 inIds) {
        QueryBean param = new QueryBean();
        return getRelationParamInOneRecord(param, param0,param3, id, inIds);
    }

    private static <T0, T1> QueryBean getRelationParamInOneRecord(QueryBean param, String param0,String param3,T0 id, T1 inIds) {
        boolean isIn = false;
        if (inIds != null){
            if (inIds instanceof Collection){
                if (!CollectionUtils.isEmpty((Collection<?>) inIds)){
                    isIn = true;
                }
            }else{
                isIn = true;
            }
        }

        if (isIn){
            QueryBean param1 = new QueryBean();
            param1.putTermField(param0, id);
            param1.putAndTermField(param3, inIds);
            param.putOrQueryBean(param1);
            QueryBean param2 = new QueryBean();
            param2.putTermField(param3, id);
            param2.putAndTermField(param0, inIds);
            param.putOrQueryBean(param2);

        } else {
            param.putOrTermField(param0, id);
            param.putOrTermField(param3, id);
        }

        return param;
    }

}
